package com.wee.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.bigtotoro.util.SharedPreferencesUtil;
import com.bigtotoro.widgets.AppProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.wee.adapter.MyTestAdapter1;
import com.wee.aircoach_user.Constant;
import com.wee.aircoach_user.MyApplication;
import com.wee.aircoach_user.PhysicalTestActivity;
import com.wee.aircoach_user.R;
import com.wee.aircoach_user.SettingActivity;
import com.wee.entity.MD5Util;
import com.wee.entity.UserHistory;
import com.wee.entity.UserHistoryResponse;
import com.wee.entity.User_detail;
import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Solomon on 2015/11/2.
 */
public class  MyFragment extends Fragment implements  View.OnClickListener{
    private View view;
    private ListView listView;
    MyTestAdapter1 adapter;
    private List<UserHistory>  history=new ArrayList<>();
    private TextView user_name,user_xingbie;
    private ImageView user_img,sex_img,first_login_img;

    /*****/
    private  User_detail data1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)

    {
        view=inflater.inflate(R.layout.activity_test, container, false);

        initView();
        return view;
    }
    private void initView() {
        ImageView imageView = (ImageView)view.findViewById(R.id.img_view);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("drawable://" + R.drawable.my_bg, imageView);
        user_name=(TextView)view.findViewById(R.id.user_name);
        user_xingbie=(TextView)view.findViewById(R.id.user_sex);
        user_img=(ImageView)view.findViewById(R.id.user_ph);
        sex_img=(ImageView)view.findViewById(R.id.sex);
        first_login_img=(ImageView)view.findViewById(R.id.first_login_img);
        view.findViewById(R.id.shezhi_wo).setOnClickListener(this);
        view.findViewById(R.id.back).setOnClickListener(this);
        view.findViewById(R.id.btn_right).setOnClickListener(this);
        view.findViewById(R.id.btn_start).setOnClickListener(this);
        listView = (ListView)view.findViewById(R.id.list);
        adapter = new MyTestAdapter1(getActivity(), history);
        listView.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadUserTest();
        loadProfileMain();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                break;
            case R.id.btn_right:
                startActivity(new Intent(getActivity(), PhysicalTestActivity.class));
                break;
            case R.id.btn_start:
                startActivity(new Intent(getActivity(), PhysicalTestActivity.class));
                break;
            case  R.id.shezhi_wo:
                try{
                if(data1.getFigure()!=null) {
                    Intent it = new Intent(getActivity(), SettingActivity.class);
                    it.putExtra("path", data1.getFigure());
                    startActivity(it);
                }else {
                    startActivity(new Intent(getActivity(), SettingActivity.class));
                       }
                }catch (Exception r){
                    Toast.makeText(getActivity(),"网络不佳",Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }
    private void loadProfileMain() {
        int exact=  SharedPreferencesUtil.getInt(getActivity(), Constant.USERTIME);
        String  user_main=Constant.USER_DETAIL+ MD5Util.md5(exact)+"&id="+ SharedPreferencesUtil.getInt(getActivity(), Constant.USERID)+ "&ver" + new Random().nextInt(9999);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, user_main,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            try {
                                data1 = gs.fromJson(object, User_detail.class);
                                user_name.setText("" + data1.getName());
                                if (data1.getGender().equals("male")) {
                               sex_img.setImageResource(R.drawable.man);
                                    user_xingbie.setText("男");
                                } else {
                                    sex_img.setImageResource(R.drawable.woman);
                                    user_xingbie.setText("女");
                                }
                                if (data1 != null) {
                                    String imgUrl = data1.getFigure();
                                    if (imgUrl != null) {
                                        ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(user_img, R.drawable.noclass_nocoach, R.drawable.noclass_nocoach);
                                        MyApplication.getInstance().getImageLoader().get(imgUrl, imageListener, 300, 300);
                                    }
                                }
                            } catch (Exception r) {
                                Toast.makeText(getActivity(),"网络不稳定",Toast.LENGTH_SHORT).show();
                            }

                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println(e.getMessage());
                    }
                });

    }
    private void loadUserTest(){
        int exact=  SharedPreferencesUtil.getInt(getActivity(), Constant.USERTIME);
        String url=Constant.USER_HISTORY+MD5Util.md5(exact)+"&userId="+SharedPreferencesUtil.getInt(getActivity(), Constant.USERID)+ "&ver" + new Random().nextInt(9999);
        RequestParams params = new RequestParams();
        AppProgressBar.checkAndCreateProgressBar(getActivity());
        MyApplication.getInstance().getHttpClient().get(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try{
                UserHistoryResponse response = new Gson().fromJson(new String(bytes), UserHistoryResponse.class);
                if(response!=null&&response.getData()!=null){
                    if(response.getData().size()!=0){
                        if(response.getData().size()==1){
                        first_login_img.setVisibility(View.VISIBLE);
                        }else{
                        first_login_img.setVisibility(View.GONE);
                        history.clear();
                        history.addAll(adapter.getCount(), response.getData());
                        adapter.notifyDataSetChanged();
                    }
                    }
                }
                AppProgressBar.closeProgressBar();
                 }catch (Exception r){
                    AppProgressBar.closeProgressBar();
                }
            }
            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                throwable.printStackTrace();
                AppProgressBar.closeProgressBar();
            }
        });
    }




}
